import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login/login.vue'
import index from '../views/index/index.vue'
import question from '../views/question/index.vue'
import movie from '../views/movie/index.vue'
import my from '../views/my/index.vue'
import notFound from '../views/notFound/index.vue'
import { getToken, removeToken } from '../utils/token'
import { Toast } from 'vant'
import { getUserInfo } from '../api/my'
import store from '../store'
import edit from '../views/edit/index.vue'
import articles from '../views/articles/index.vue'
import search from '../views/search/index.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: login
  },
  {
    path: '/index',
    component: index,
    meta: {
      showTab: true
    }
  },
  {
    path: '/articles:id',
    name: 'articles',
    component: articles
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '/edit',
    component: edit,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/question',
    component: question,
    meta: {
      showTab: true
    }
  },
  {
    path: '/movie',
    component: movie,
    meta: {
      showTab: true
    }
  },
  {
    path: '/my',
    component: my,
    meta: {
      showTab: true,
      needLogin: true
    }
  },
  {
    path: '/notFound',
    component: notFound
  },
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '*',
    redirect: '/notFound'
  }
]

// 处理路由切换的Promise的reject错误
// 吞掉 没有处理的 promise的错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 执行之后 阻断后续代码
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  // to里面能拿到跳转前的路由信息
  console.log('to', to)
  // 不需要登录的页面
  if (to.meta.needLogin === undefined) {
    return next()
  }
  // 需要登录的页面，检查是否有token，如果没有，则提示登录，跳转登录页
  const tokenObj = getToken()
  if (tokenObj === null) {
    Toast.fail('请先登录')
    return next({ path: '/login', query: { back: to.path } }) // 路由传值，配置写法；跳转到登录页面后需要接参this.$route.query.back,登录后跳转到原来路由页面
  }
  // 已经登录，每次跳转页面都会发送ajax，如果仓库有数据，就直接跳转，不需要执行后面的请求getUserInfo()
  if (store.state.userInfo.name) {
    return next()
  }

  // 发送获取用户信息ajax请求。如果有token就能成功获取用户信息，就会进入then里面，
  // 如果没有token或者token错误，则会进入catch里面
  getUserInfo()
    .then(data => {
      store.commit('setUserInfo', data.data.data)
      next()
    })
    .catch(errRes => {
      // console.log(errRes)
      if (errRes.response.status === 401) {
        removeToken()
        Toast.fail('请先登录')
        next({ path: '/login', query: { back: to.path } })
      }
    })
})
export default router
